using System;
using System.Threading.Tasks;
using IntegratedMeasuring.ViewModels.Scheme;

namespace IntegratedMeasuring.Storage;

/// <summary>
/// 日志数据存储操作工具类
/// 提供对日志数据库的增删改查操作
/// </summary>
public class LogDataStorage : BaseStorage
{
    private static readonly LogDataStorage _instance = new LogDataStorage();

    private LogDataStorage() : base($"DataSource={IntegratedMeasuring.ViewModels.Entity.GC.LogDbFilePath}")
    {
    }

    /// <summary>
    /// 获取单例实例
    /// </summary>
    public static LogDataStorage Instance => _instance;

    /// <summary>
    /// 清理指定日期之前的日志
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">删除条件表达式</param>
    /// <returns>删除的记录数</returns>
    public int CleanOldLogs<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Deleteable<T>().Where(expression).ExecuteCommand();
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return 0;
            }
        }
    }

    /// <summary>
    /// 异步清理指定日期之前的日志
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <param name="expression">删除条件表达式</param>
    /// <returns>删除的记录数</returns>
    public async Task<int> CleanOldLogsAsync<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
    {
        return await Task.Run(() => CleanOldLogs(expression));
    }
    
    public override void InitRuntimeTables()
    { 
        _db.DbMaintenance.CreateDatabase();
        _db.CodeFirst.InitTables<LogRecord>();
    }
    
    public bool SaveLogRecord(LogRecord log)
    {
        lock (_writeLock)
        {
            try
            {
                return _db.Insertable(log).ExecuteCommand() > 0;
            }
            catch (Exception ex)
            {
                // TODO: 记录日志
                return false;
            }
        }
    }
} 